package com.tz.cartelo.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.utils.StorageUtils;
import com.tz.cartelo.R;
import com.tz.cartelo.constant.Api;
import com.tz.cartelo.constant.Key;
import com.tz.cartelo.model.DataParams;
import com.tz.cartelo.util.CommonUtils;
import com.tz.common.util.LogUtil;
import com.tz.common.util.PreferencesUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by tz on 2016/8/3.
 */

public class LoadingPageActivity extends DataLoadActivity {
    private static final String TAG = "LoadingPageActivity";
    private static final int HANDLER_TIMER = 1;
    private int countdown = 4;
    private ProgressDialog progressDialog;
    private Activity parentActivity;
    private File apkFilePath;
    private Timer mTimer;
    private MyTimerTask myTimerTask;
    private TextView mLoadingViewPageSkip;
    private boolean mGetMessageSucceed;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_loading_page;
    }

    @Override
    protected void init() {
        ImageView mLoadingImg = (ImageView) findViewById(R.id.loading_img);
        mLoadingImg.setImageResource(R.mipmap.ic_loading_img);
        mLoadingViewPageSkip = (TextView) findViewById(R.id.loading_view_page_skip);
        mLoadingViewPageSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeTimer();
            }
        });

        if (isNetworkConnected()) {
            mGetMessageSucceed = true;
            openTimer();
//            if (CommonUtils.isWifiConnected(this)) {//wifi情况下静默更新
//                silenceUpdateAction(this);
//            } else {
//            cpUpdateCheck(this, new MyCPCheckUpdateCallback());
//            }
        } else {
            setNetworkMethod(LoadingPageActivity.this);
        }
    }

    @Override
    protected void initTitle() {

    }

    @Override
    protected void initParams(DataParams params) {
        params.addParam("version_name", CommonUtils.getVersionName(this));
        params.addParam("version_code", CommonUtils.getVersionCode(this) + "");
    }

//    private class MyCPCheckUpdateCallback implements CPCheckUpdateCallback {
//        @Override
//        public void onCheckUpdateCallback(AppUpdateInfo appUpdateInfo, AppUpdateInfoForInstall appUpdateInfoForInstall) {
//            if (null == appUpdateInfo && null == appUpdateInfoForInstall) {
//                openTimer();
//            } else {
//                if (appUpdateInfo != null) {
//                    if (appUpdateInfo.getAppVersionCode() > CommonUtils.getVersionCode(LoadingPageActivity.this)) {
//                        downLoad(appUpdateInfo, appUpdateInfo.getAppChangeLog());
//                    } else {
//                        openTimer();
//                    }
//                }
//            }
//        }
//    }

    @Override
    protected void disposeResult(Api api, String response) {
        LogUtil.d(TAG, response);
        switch (api) {
            case CHECK_UP_DATA:
                /*
                ResultCheckUpData resultCheckUpData = fromJson(response, ResultCheckUpData.class);
                if (!resultCheckUpData.isSuccess()) {
                    showToast(resultCheckUpData.getError());

                    mLoadingViewPageSkip.setVisibility(View.VISIBLE);
                    mTimer = new Timer();
                    if (myTimerTask == null) {
                        myTimerTask = new MyTimerTask();
                        mTimer.schedule(myTimerTask, 0, 1000); //延时0ms后执行，1000ms执行一次
                    }
                    return;
                }
                mGetMessageSucceed = true;
                CheckUpData checkUpData = resultCheckUpData.getCheckUpData();
                switch (checkUpData.getUpdate_type()) {
                    case Key.CHECK_UP_DATA_NO:
//                        startActivity();
                        mLoadingViewPageSkip.setVisibility(View.VISIBLE);
                        mTimer = new Timer();
                        if (myTimerTask == null) {
                            myTimerTask = new MyTimerTask();
                            mTimer.schedule(myTimerTask, 0, 1000); //延时0ms后执行，1000ms执行一次
                        }
                        break;
                    case Key.CHECK_UP_DATA_CAN:
                        downLoad(checkUpData.getDownload_address(), checkUpData.getUpdate_message());
                        break;
                    case Key.CHECK_UP_DATA_MAST:
                        VersionUpdateUtils(LoadingPageActivity.this, checkUpData.getDownload_address());
                        break;
                    default:
                        break;
                }
                */
                break;
            default:
                break;
        }
    }

    private class MyTimerTask extends TimerTask {
        @Override
        public void run() {
            Message message = new Message();
            message.what = HANDLER_TIMER;
            timeHandler.sendMessage(message);
        }
    }

    private void openTimer() {
        mLoadingViewPageSkip.setVisibility(View.VISIBLE);
        mTimer = new Timer();
        if (myTimerTask == null) {
            myTimerTask = new MyTimerTask();
            mTimer.schedule(myTimerTask, 0, 1000); //延时0ms后执行，1000ms执行一次
        }
    }

    private void closeTimer() {
        if (myTimerTask != null && mTimer != null) {
            myTimerTask.cancel(); //退出计时器
            myTimerTask = null;
            if (PreferencesUtils.getBoolean(Key.PER_LOGIN, false))
                switchActivityAndFinish(MainActivity.class, null);
            else
                switchActivityAndFinish(LoginActivity.class, null);
        }
    }

    private Handler timeHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_TIMER:
                    countdown--;
                    mLoadingViewPageSkip.setText(getString(R.string.loading_page_skip) + " " + countdown);
                    if (HANDLER_TIMER == countdown) {
                        if (myTimerTask != null && mTimer != null) {
                            myTimerTask.cancel(); //退出计时器
                            myTimerTask = null;
                            if (PreferencesUtils.getBoolean(Key.PER_LOGIN, false))
                                switchActivityAndFinish(MainActivity.class, null);
                            else
                                switchActivityAndFinish(LoginActivity.class, null);
                        }
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };


    private void startActivity() {
        new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switchActivityAndFinish(MainActivity.class, null);
            }
        }.sendEmptyMessageDelayed(0, 2000);
    }

    /**
     * 打开设置网络界面
     */
    private void setNetworkMethod(final Context context) {
        // 提示对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(getString(R.string.loading_page_dialog_title))
                .setMessage(getString(R.string.loading_page_dialog_set_net))
                .setPositiveButton(getString(R.string.sure), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = null;
                        // 判断手机系统的版本 即API大于10 就是3.0或以上版本
                        if (android.os.Build.VERSION.SDK_INT > 10) {
                            intent = new Intent(
                                    android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                        } else {
                            intent = new Intent();
                            ComponentName component = new ComponentName(
                                    "com.android.settings",
                                    "com.android.settings.WirelessSettings");
                            intent.setComponent(component);
                            intent.setAction("android.intent.action.VIEW");
                        }
                        context.startActivity(intent);
                        // 退出当前应用
                        int pid = android.os.Process.myPid();
                        android.os.Process.killProcess(pid); // 杀死当前进程
                    }
                })
                .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        int pid = android.os.Process.myPid();
                        android.os.Process.killProcess(pid); // 杀死当前进程
                    }
                }).show();
    }

    /*
    private void downLoad(final AppUpdateInfo appUpdateInfo, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        builder.setTitle(getString(R.string.loading_page_dialog_message));
        builder.setMessage(message);
        builder.setPositiveButton(getString(R.string.sure), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                VersionUpdateUtils(LoadingPageActivity.this, url);
                cpUpdateDownload(LoadingPageActivity.this, appUpdateInfo, new MyCPUpdateDownloadCallback());

            }
        });
        builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(
                    DialogInterface dialog,
                    int which) {
                switchActivityAndFinish(MainActivity.class, null);
            }
        });
        builder.show();
    }
*/
    /*
    private class MyCPUpdateDownloadCallback implements CPUpdateDownloadCallback {
        @Override
        public void onStart() {
            parentActivity = LoadingPageActivity.this;
            progressDialog = new ProgressDialog(LoadingPageActivity.this);

            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setTitle(getString(R.string.loading_page_dialog_title));
            progressDialog.setMessage(getString(R.string.loading_page_dialog_download));
            progressDialog.setProgress(0);
            progressDialog.setMax(100);
            progressDialog.show();
        }

        @Override
        public void onPercent(int i, long l, long l1) {
            handler.sendEmptyMessage(i);
        }

        @Override
        public void onDownloadComplete(String s) {
            cpUpdateInstall(LoadingPageActivity.this, s);
        }

        @Override
        public void onFail(Throwable throwable, String s) {
            showToast(R.string.check_update_down_load_fails);
        }

        @Override
        public void onStop() {

        }
    }
    */

    private void VersionUpdateUtils(final Activity activity, final String apkDownloadURL) {
        System.out.println("apkDownloadURL=" + apkDownloadURL);
        parentActivity = activity;
        progressDialog = new ProgressDialog(activity);
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String fileName = getString(R.string.app_file_name);
                    // apkDownloadURL.substring( apkDownloadURL.lastIndexOf("/")
                    // + 1, apkDownloadURL.length());
                    if (!URLUtil.isNetworkUrl(apkDownloadURL)) {
                        showToast(R.string.network_ungelivable);
                        return;
                    } else {
                        URL downloadURL = new URL(apkDownloadURL);
                        HttpURLConnection urlConnection = (HttpURLConnection) downloadURL
                                .openConnection();
                        urlConnection.connect();

                        int fileLength = urlConnection.getContentLength();
                        InputStream input = urlConnection.getInputStream(); // 没有缓存机制的IO
                        // InputStream input = new
                        // BufferedInputStream(downloadURL.openStream());

                        // 把apk放在系统的下载目录
                        File downloadPath = StorageUtils.getOwnCacheDirectory(LoadingPageActivity.this,
                                getString(R.string.file_name));
//                        File downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                        downloadPath.mkdirs();

                        apkFilePath = new File(downloadPath, fileName);

                        FileOutputStream output = new FileOutputStream(
                                apkFilePath);
                        byte buf[] = new byte[1024];
                        long total = 0;
                        int length;
                        while ((length = input.read(buf)) > 0) {
                            total += length;
                            handler.sendEmptyMessage((int) (total * 100 / fileLength));
                            output.write(buf, 0, length);
                        }
                        // urlConnection.disconnect();
                        input.close();
                        output.close();
                    }
                } catch (Exception e) {
                    System.out.println("Exception" + e.getMessage()
                            + "--------------" + e);
                }
            }
        });

        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setTitle(getString(R.string.loading_page_dialog_title));
        progressDialog.setMessage(getString(R.string.loading_page_dialog_download));
        progressDialog.setProgress(0);
        progressDialog.setMax(100);
        progressDialog.show();
        thread.start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what >= 100) {
                // 安装apk
                progressDialog.cancel();
                parentActivity.finish();
                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setAction(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(apkFilePath),
                        "application/vnd.android.package-archive");
                parentActivity.startActivity(intent);
            }
            progressDialog.setProgress(msg.what);
            super.handleMessage(msg);
        }
    };

    @Override
    public void onBackPressed() {
        if (!mGetMessageSucceed)
            finish();
    }
}
